﻿
package
	{
	import flash.events.*;
	import flash.net.*;
	import flash.utils.Timer;
	import flash.display.MovieClip;
	
	class Client
		{
		var stageMc:MovieClip;
		var myLogin:String;
		var chrono:Timer;
		var connexion:Socket = new Socket();
		var players:Object;
		
		function Client(Adresse:String, port:Number, players:Object, stageMc:MovieClip)
			{
			this.stageMc = stageMc;
			this.players = players;
			chrono = new Timer(200);
			connexion = new Socket();
			// écoute des événements
			connexion.connect(Adresse, port);
			connexion.addEventListener ( Event.CONNECT, connectionSucess);
			connexion.addEventListener ( Event.CLOSE, connectionClosed );
			connexion.addEventListener ( ProgressEvent.SOCKET_DATA, dataReceived);
			
			chrono.addEventListener(TimerEvent.TIMER, envois_donne);
			chrono.start();
			}
		
		function envois_donne( e:TimerEvent ):void
			{
			players[0].stateToBit();
			connexion.writeUTF ('<login>'+ myLogin +'</login><x>'+players[0].x+'</x><y>'+players[0].y+'</y><rotation>'+players[0].torso.rotation+'</rotation><bitField>'+players[0].bitField+'</bitField>');
			connexion.flush();
			}
		
		function connectionSucess (pEvt:Event):void
			{
			connexion.writeUTFBytes("<hello/>");
			connexion.flush();
			}
		
		function connectionClosed ( pEvt:Event ):void
			{
			//delete(this);
			//chat.appendText("fermeture de la connexion");
			}
		
		function dataReceived ( pEvt:ProgressEvent ):void
			{
			var msg = connexion.readUTFBytes(connexion.bytesAvailable);
			var xml:XML = new XML('<root>'+msg+'</root>');
			
			if (xml.hasOwnProperty('x'))
				{
				if (!this.players.hasOwnProperty(xml.login))
					{
					trace (xml);
					this.players[xml.login] = new Player(null);
					stageMc.addChild(this.players[xml.login]);
					this.players[xml.login].addEvents();
					}
				
				if (xml.login != this.myLogin)
					{
					this.players[xml.login].x = xml.x;
					this.players[xml.login].y = xml.y;
					this.players[xml.login].destinationAngle = xml.rotation;
					this.players[xml.login].bitField = xml.bitField;
					}
				}
			else
				{
				this.myLogin = xml.login;
				}
			}
		}
	}